import React, { useState, useEffect } from 'react';
import { 
  Card, 
  Table, 
  Input, 
  Button, 
  Space, 
  message,
  Modal,
  Form,
  Select,
  DatePicker,
  Tag
} from 'antd';
import { 
  SearchOutlined, 
  EyeOutlined,
  RedoOutlined
} from '@ant-design/icons';
import { history, useModel } from '@umijs/max';
import { getBorrowings, getBorrowingDetail, returnBook, renewBorrowing } from '@/services/BorrowingAPI';
import { getUsers } from '@/services/userApi';
import { getBooks } from '@/services/bookAPi';
import { BorrowingItem } from '@/types/borrowing';

const { RangePicker } = DatePicker;
const { Option } = Select;

const BorrowingList: React.FC = () => {
  const [borrowings, setBorrowings] = useState<BorrowingItem[]>([]);
  const [loading, setLoading] = useState(false);
  const [users, setUsers] = useState<any[]>([]);
  const [books, setBooks] = useState<any[]>([]);
  const [searchForm] = Form.useForm();
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });

  const { initialState } = useModel('@@initialState');
  const currentUser = initialState?.currentUser;

  // 获取借阅记录列表
  const fetchBorrowings = async (params = {}) => {
    setLoading(true);
    try {
      const { current = 1, pageSize = 10 } = pagination;
      const searchParams = {
        page: current,
        page_size: pageSize,
        ...params,
      };

      // 如果不是管理员，只显示自己的借阅记录
      if (currentUser?.role !== 'admin' && currentUser?.role !== 'librarian') {
        searchParams.user = currentUser?.id;
      }

      const res = await getBorrowings(searchParams);
      setBorrowings(res.data.results);
      setPagination({
        ...pagination,
        total: res.data.count,
      });
    } catch (error) {
      message.error('获取借阅记录失败');
    } finally {
      setLoading(false);
    }
  };

  // 获取用户列表
  const fetchUsers = async () => {
    try {
      const res = await getUsers();
      setUsers(res.data.results);
    } catch (error) {
      message.error('获取用户列表失败');
    }
  };

  // 获取图书列表
  const fetchBooks = async () => {
    try {
      const res = await getBooks();
      setBooks(res.data.results);
    } catch (error) {
      message.error('获取图书列表失败');
    }
  };

  useEffect(() => {
    fetchBorrowings();
    
    // 管理员和图书管理员可以查看所有记录，需要用户和图书列表
    if (currentUser?.role === 'admin' || currentUser?.role === 'librarian') {
      fetchUsers();
      fetchBooks();
    }
  }, [pagination.current, pagination.pageSize, currentUser]);

  // 搜索
  const handleSearch = (values: any) => {
    const params = {
      ...values,
      borrow_date_min: values.borrow_date ? values.borrow_date[0] : undefined,
      borrow_date_max: values.borrow_date ? values.borrow_date[1] : undefined,
    };
    delete params.borrow_date;
    fetchBorrowings(params);
  };

  // 重置搜索
  const handleReset = () => {
    searchForm.resetFields();
    fetchBorrowings();
  };

  // 查看详情
  const handleView = (id: number) => {
    history.push(`/borrowing/detail/${id}`);
  };

  // 续借
  const handleRenew = async (id: number) => {
    try {
      await BorrowingAPI.renewBorrowing(id);
      message.success('续借成功');
      fetchBorrowings();
    } catch (error) {
      message.error('续借失败');
    }
  };

  // 状态标签
  const renderStatusTag = (status: string) => {
    const statusMap = {
      borrowed: { color: 'blue', text: '借阅中' },
      returned: { color: 'green', text: '已归还' },
      overdue: { color: 'red', text: '已逾期' },
    };
    const statusInfo = statusMap[status as keyof typeof statusMap] || { color: 'default', text: status };
    return <Tag color={statusInfo.color}>{statusInfo.text}</Tag>;
  };

  // 表格列定义
  const columns = [
    {
      title: '用户',
      dataIndex: 'user',
      key: 'user',
      render: (user: any) => user?.username || '-',
    },
    {
      title: '图书',
      dataIndex: 'book',
      key: 'book',
      render: (book: any) => book?.title || '-',
    },
    {
      title: '借阅日期',
      dataIndex: 'borrow_date',
      key: 'borrow_date',
    },
    {
      title: '应还日期',
      dataIndex: 'due_date',
      key: 'due_date',
    },
    {
      title: '实际归还日期',
      dataIndex: 'return_date',
      key: 'return_date',
      render: (return_date: string) => return_date || '-',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => renderStatusTag(status),
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: BorrowingItem) => (
        <Space>
          <Button 
            type="link" 
            icon={<EyeOutlined />} 
            onClick={() => handleView(record.id)}
          >
            查看
          </Button>
          {(record.status === 'borrowed' || record.status === 'overdue') && (
            <Button 
              type="link" 
              icon={<RedoOutlined />} 
              onClick={() => handleRenew(record.id)}
            >
              续借
            </Button>
          )}
        </Space>
      ),
    },
  ];

  // 如果是普通用户，隐藏用户列
  const filteredColumns = (currentUser?.role !== 'admin' && currentUser?.role !== 'librarian') 
    ? columns.filter(col => col.key !== 'user')
    : columns;

  return (
    <div>
      <Card>
        <div style={{ marginBottom: 16 }}>
          <Form
            form={searchForm}
            layout="inline"
            onFinish={handleSearch}
          >
            {(currentUser?.role === 'admin' || currentUser?.role === 'librarian') && (
              <>
                <Form.Item name="user" label="用户">
                  <Select
                    placeholder="请选择用户"
                    style={{ width: 150 }}
                    allowClear
                  >
                    {users.map(user => (
                      <Option key={user.id} value={user.id}>
                        {user.username}
                      </Option>
                    ))}
                  </Select>
                </Form.Item>
                
                <Form.Item name="book" label="图书">
                  <Select
                    placeholder="请选择图书"
                    style={{ width: 200 }}
                    allowClear
                    showSearch
                    optionFilterProp="children"
                  >
                    {books.map(book => (
                      <Option key={book.id} value={book.id}>
                        {book.title}
                      </Option>
                    ))}
                  </Select>
                </Form.Item>
              </>
            )}
            
            <Form.Item name="status" label="状态">
              <Select
                placeholder="请选择状态"
                style={{ width: 120 }}
                allowClear
              >
                <Option value="borrowed">借阅中</Option>
                <Option value="returned">已归还</Option>
                <Option value="overdue">已逾期</Option>
              </Select>
            </Form.Item>
            
            <Form.Item name="borrow_date" label="借阅日期">
              <RangePicker style={{ width: 240 }} />
            </Form.Item>
            
            <Form.Item>
              <Space>
                <Button type="primary" icon={<SearchOutlined />} htmlType="submit">
                  搜索
                </Button>
                <Button onClick={handleReset}>
                  重置
                </Button>
              </Space>
            </Form.Item>
          </Form>
        </div>

        <Table
          columns={filteredColumns}
          dataSource={borrowings}
          rowKey="id"
          loading={loading}
          pagination={{
            ...pagination,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条`,
            onChange: (page, pageSize) => {
              setPagination({
                ...pagination,
                current: page,
                pageSize: pageSize,
              });
            },
          }}
        />
      </Card>
    </div>
  );
};

export default BorrowingList;